package cz.anime.ppro.beans;

import java.io.IOException;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;

import cz.anime.ppro.enums.UserRolesEnum;
import cz.anime.ppro.logic.EventComponent;
import cz.anime.ppro.logic.UserComponent;
import cz.anime.ppro.model.Event;

@Component
@ManagedBean
@Scope(WebApplicationContext.SCOPE_REQUEST)
public class EventListBean {
	
	private boolean admin = false;
	
	private List<Event> events;
	
	@Autowired
	private EventComponent eventComponent;
	
	@Autowired
	private UserComponent userComponent;
	
	@PostConstruct
	public void init(){
		events = eventComponent.getEvents();
		
		if (userComponent.getUser(getCurrentUser()).getRole().equals(UserRolesEnum.ROLE_ADMIN.name())) {
			admin = true;
		}
	}
	
	public int getCurrentUser(){
		return userComponent.getUserByNick(userComponent.getCurrentUsernameFromSession()).getId();
	}
	
	public void deleteEvent(int eventId){	
		
		Event delevent = eventComponent.getEvent(eventId);
		eventComponent.deleteEvent(delevent);
		getEvents().remove(delevent);
		
		try {
			FacesContext.getCurrentInstance().getExternalContext().redirect("/PPRO2/event-list.jsf");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public String redirect(){
		return "event";
	}

	public List<Event> getEvents() {
		return events;
	}

	public void setEvents(List<Event> events) {
		this.events = events;
	}

	public boolean isAdmin() {
		return admin;
	}

	public void setAdmin(boolean admin) {
		this.admin = admin;
	}
	
}
